//
//  SelectCityViewController.m
//  lvtu
//
//  Created by Apple on 12-4-4.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SelectCityViewController.h"
#import <QuartzCore/QuartzCore.h>

static NSInteger SortByLetter(id s1, id s2, void *context)
{
	NSString * ws1 = s1;
	NSString * ws2 = s2;
    
    if ([ws1 intValue] < [ws2 intValue])
        return NSOrderedDescending;
    else if ([ws1 intValue] > [ws2 intValue])
        return NSOrderedAscending;
    else
        return NSOrderedSame;
}

@implementation SelectCityViewController
@synthesize isEdit;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.title = @"修改地点";
    UILabel* tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    [tempLabel setText:@"修改地点"];
    [tempLabel setBackgroundColor:[UIColor clearColor]];
    [tempLabel setTextAlignment:UITextAlignmentCenter];
    [tempLabel setTextColor:[UIColor colorWithRed:111/255.0 green:117/255.0 blue:81/255.0 alpha:1.0]];
    [tempLabel setFont:[UIFont boldSystemFontOfSize:20]];
    self.navigationItem.titleView = tempLabel;
    [tempLabel release];
    tempLabel = nil;
    
    UIImage* backImage = [UIImage imageNamed:@"btn_back_normal.png"];
    UIButton* leftbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftbutton.frame = CGRectMake(0, 0, backImage.size.width, backImage.size.height);
    [leftbutton setBackgroundImage:backImage forState:UIControlStateNormal];
    [leftbutton setBackgroundImage:[UIImage imageNamed:@"btn_back_press.png"] forState:UIControlStateHighlighted];
    [leftbutton addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftbutton];
    //signupButton.image = [UIImage imageNamed:@"btn_finish_normal.png"];
    self.navigationItem.leftBarButtonItem = backButtonItem;
    [backButtonItem release];
    
    UIImage* okImage = [UIImage imageNamed:@"btn_finish_normal.png"];
    UIButton* rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightbutton.frame = CGRectMake(0, 0, okImage.size.width, okImage.size.height);
    [rightbutton setBackgroundImage:okImage forState:UIControlStateNormal];
    [rightbutton setBackgroundImage:[UIImage imageNamed:@"btn_finish_press.png"] forState:UIControlStateHighlighted];
    
    [rightbutton addTarget:self action:@selector(okButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* okButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightbutton];
    self.navigationItem.rightBarButtonItem = okButtonItem;
    [okButtonItem release];
    
    UILabel* mailLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 60, 30)];
    mailLabel.text = @"选择城市：";
    mailLabel.font = [UIFont systemFontOfSize:11];
    mailLabel.backgroundColor = [UIColor clearColor];
    mailLabel.textColor = [UIColor colorWithRed:122/255.0 green:143/255.0 blue:68/255.0 alpha:1];
    [self.view addSubview:mailLabel];
    [mailLabel release];
    
    citynameTextField = [[UITextField alloc] init];
    UIImage* TextFieldImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg_imput.png" ofType:nil]];
    UIImageView* textFieldBackImageView = [[UIImageView alloc] initWithFrame:CGRectMake(70, 10, 230, 30)];
    textFieldBackImageView.image = TextFieldImage;
    [self.view addSubview:textFieldBackImageView];
    [textFieldBackImageView release];
    
    [citynameTextField setFrame:CGRectMake(80, 10, 200, 30)];
    //[citynameTextField setBackground:TextFieldImage];
    citynameTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;                
    [citynameTextField setAutocorrectionType:UITextAutocorrectionTypeDefault];
    [citynameTextField setReturnKeyType:UIReturnKeySearch];
    [citynameTextField setFont:[UIFont boldSystemFontOfSize:15]];
    [citynameTextField setDelegate:self];
    [citynameTextField setPlaceholder:@""];
    [citynameTextField setTextColor:[UIColor colorWithRed:254/255.0 green:85/255.0 blue:0/255.0 alpha:1.0]];
    [citynameTextField setTextAlignment:UITextAlignmentCenter];
    [citynameTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [citynameTextField setClipsToBounds:YES];
    [self.view addSubview:citynameTextField];
    [citynameTextField release];
    
//    cityView =[[WKCityInputView alloc] initWithFrame:CGRectMake(44, 96, 240, 240)];
//	cityView.userInteractionEnabled = YES;
//    [[cityView layer] setBorderColor:[[UIColor lightGrayColor] CGColor]];
//    [[cityView layer] setBorderWidth:1.0];
//    [[cityView layer] setCornerRadius:4];
//	cityView.delegate = self;
//    [cityView setCityInfo:nil];
//    [self.view addSubview:cityView];
    
    UIImage *bgImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg_whiteframe.png" ofType:nil]];
    UIImageView* tableBgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 45, 280, 335
                                                                                  )];
    [tableBgImageView setImage:[bgImage stretchableImageWithLeftCapWidth:30 topCapHeight:20]];
    [bgImage release];
    [self.view addSubview:tableBgImageView];
    [tableBgImageView release];
    
    if (self.view.frame.size.height > 480) {
        cityTableView = [[UITableView alloc] initWithFrame:CGRectMake(25, 45, 270, 410) style:UITableViewStylePlain];
    }
    else
    {
        cityTableView = [[UITableView alloc] initWithFrame:CGRectMake(25, 45, 270, 330) style:UITableViewStylePlain];
    }
    
    cityTableView.backgroundColor = [UIColor clearColor];
    cityTableView.delegate = self;
    cityTableView.dataSource = self;
    [self.view addSubview:cityTableView];
    
    cityArray = [[NSMutableArray alloc] init];
    [cityArray addObjectsFromArray:[DataSource shareInstance].cityArray];
}

- (void)viewDidUnload
{
    [cityArray release];cityArray = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return NO;
}

- (void)backButtonPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)okButtonPress:(id)sender
{
    for (CityInfo* city in [DataSource shareInstance].cityArray) {
        if ([citynameTextField.text isEqualToString:city.name]) {
            info = city;
            break;
        }
    }
    [[DataSource shareInstance] setDefaultCityInfo:info];
    NSDictionary* dict = [[NSDictionary alloc] initWithObjectsAndKeys:citynameTextField.text,@"name", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:UpdateCitySelect object:self userInfo:dict];
    [self.navigationController popViewControllerAnimated:YES];
    [dict release];
}

- (void)CitySeleted:(CityInfo *)Info
{
    info = Info;
    [citynameTextField setText:info.name];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
//    NSInteger count = [[[DataSource shareInstance].cityDict allKeys] count];
    return 27;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"热门城市";
    }
    char c = 'A';
    return [NSString stringWithFormat:@"%c",c+section-1];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (section == 0) {
        return [[[DataSource shareInstance].cityDict objectForKey:@"hot"] count];
    }
    char c = 'A';
    return [[[DataSource shareInstance].cityDict objectForKey:[NSString stringWithFormat:@"%c",c+section-1]] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    
//    CityInfo* cityInfo = (CityInfo*)[cityArray objectAtIndex:indexPath.row];
    char c = 'A';
    NSArray* array = [[DataSource shareInstance].cityDict objectForKey:[NSString stringWithFormat:@"%c",c+indexPath.section-1]];
    if(indexPath.section == 0)
    {
        array = [[DataSource shareInstance].cityDict objectForKey:@"hot"];
    }
    NSDictionary* city = [array objectAtIndex:indexPath.row];
    cell.textLabel.text = [city objectForKey:@"name"];
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    //[tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"index = %d",indexPath.row);
    char c = 'A';
    NSArray* array = [[DataSource shareInstance].cityDict objectForKey:[NSString stringWithFormat:@"%c",c+indexPath.section-1]];
    if(indexPath.section == 0)
    {
        array = [[DataSource shareInstance].cityDict objectForKey:@"hot"];
    }
    
    NSDictionary* city = [array objectAtIndex:indexPath.row];
    [citynameTextField setText:[city objectForKey:@"name"]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    return 35;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *toBeReturned = [[NSMutableArray alloc]init];
    [toBeReturned addObject:@"热门城市"];
    for(char c = 'A';c <= 'Z';c++)
    {
        [toBeReturned addObject:[NSString stringWithFormat:@"%c",c]];
    }
    return toBeReturned;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
//    NSString* keyword;
//    if ([title isEqualToString:@"热门城市"]) {
//        keyword = @"hot";
//    }
//    else{
//        keyword = title;
//    }
//    NSInteger count = 0;
//    for(NSDictionary *character in [[DataSource shareInstance].cityDict objectForKey:keyword])
//    {
//        if([[character objectForKey:@"pinyin" ] isEqualToString:title])
//        {
//            return count;
//        }
//        
//        count ++;
//    }
//    return 0;
    return index;
}

#pragma -mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == citynameTextField && [citynameTextField.text isEqualToString:@"请输入城市名称"])
    {
        [citynameTextField setText:@""];
        [citynameTextField setTextColor:[UIColor blackColor]];
    }
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [citynameTextField resignFirstResponder];
    if ( textField == citynameTextField && [citynameTextField.text isEqualToString:@""])
    {
        [citynameTextField setPlaceholder:@"请输入城市名称"];
        [citynameTextField setTextColor:[UIColor grayColor]];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (1 == range.length) {//按下回格键
        return YES;
    }
    
    if ([string isEqualToString:@"\n"])
    {//按下return键
        //这里隐藏键盘，不做任何处理
        [textField resignFirstResponder];
        //        [self willLoginWeibo];
        return NO;
    }
    else
    {
        return YES;
    }
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == citynameTextField)
    {
        [citynameTextField setText:@""];
        [citynameTextField setPlaceholder:@"请输入城市名称"];
        [citynameTextField setTextColor:[UIColor grayColor]];
    }
    return YES;
}

- (void)onDataSourceSucCallback:(CoreMsg *)coreMsg withData:(id)data
{
    NSLog(@"suc");
}

- (void)onDataSourceFailCallback:(CoreMsg *)coreMsg withData:(id)data
{
    NSLog(@"fail");
}

@end
